import React, { useEffect, useState } from 'react';
import './PrescriptionManage2.css';
import { Table, Modal, Input, Button, message } from 'antd';
import { FileTextOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';


export default function IntegratedManage() {
    const [doctor, setDoctor] = useState('')  // 查询医生
    const [department, setDepartment] = useState('')  // 查询科室
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);  // 选中项
    const [loading, setLoading] = useState(false);
    const [detailModalOpen, setEditModalOpen] = useState(false)  // 编辑弹窗
    const [TipModalOpen, setTipModalOpen] = useState(false)  // 删除弹窗提示
    const [currentId, setCurrentId] = useState(null)  // 当前点击项id

    const doctorChange = (e) => {  // 查询医生输入框变化
        setDoctor(e.target.value)
    }
    const departmentChange = (e) => {  // 查询科室输入框变化
        setDepartment(e.target.value)
    }
    const queryBtn = () => {  // 查询按钮
        // console.log(doctor, department)
        // axios.get('http://8.148.7.123:8000/recipel/list', {
        //     params: {
        //         page: 1,
        //         size: 100,
        //         doctor: doctor,
        //         department: department,
        //     }
        // }).then(res => { 
        //     console.log(res.data)
        // })
        // 接口有问题，手写一个查询
        if (!doctor && !department) {  // 都为空，查询全部
            getTableData()
            return
        } else if (doctor !== '' && department !== '') {  // 都不为空，查询指定医生和科室
            axios.get('http://8.148.7.123:8000/recipel/list', {
                params: {
                    page: 1,
                    size: 100,
                }
            }).then(res => {
                setTableData(() => {
                    return res.data.data.map(item => {
                        return {
                            ...item,
                            price: item.price.toFixed(2),  // 金额保留两位小数
                        }
                    })
                })
                // 查询全部
                setTableData(tableData.filter(item => item.name.indexOf(doctor) !== -1 && item.department.indexOf(department) !== -1))
            })
            return
        } else if (doctor && !department) {  // 只输入医生
            axios.get('http://8.148.7.123:8000/recipel/list', {
                params: {
                    page: 1,
                    size: 100,
                }
            }).then(res => {
                setTableData(() => {
                    return res.data.data.map(item => {
                        return {
                            ...item,
                            price: item.price.toFixed(2),  // 金额保留两位小数
                        }
                    })
                })
                // 查询医生
                setTableData(tableData.filter(item => item.name.indexOf(doctor) !== -1))
            })
            return
        } else if (department && !doctor) {  // 只输入科室
            axios.get('http://8.148.7.123:8000/recipel/list', {
                params: {
                    page: 1,
                    size: 100,
                }
            }).then(res => {
                setTableData(() => {
                    return res.data.data.map(item => {
                        return {
                            ...item,
                            price: item.price.toFixed(2),  // 金额保留两位小数
                        }
                    })
                })
                // 查询科室
                setTableData(tableData.filter(item => item.department.indexOf(department) !== -1))
            })
            return
        }
    }

    const delChecked = () => {  // 批量删除
        setLoading(true);
        setTimeout(() => {
            axios.post('http://8.148.7.123:8000/recipel/batchdel', {
                ids: selectedRowKeys
            }).then(res => {
                if (res.data.code === 1) {
                    message.success('删除成功')
                } else {
                    message.error('删除失败')
                }
                getTableData();  // 更新表格数据
            })
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    }
    const detail = async (id) => {  // 详情按钮
        setEditModalOpen(true)
        await axios.get('http://8.148.7.123:8000/recipel/infobyid', {
            params: {
                id: id,
            }
        }).then(res => {
            // console.log(res.data.data[0])
            const data = JSON.parse(res.data.data[0].recipel.replace(/'/g, '"'))
            // console.log(data)
            setDetailTableData(() => {
                return data.map(item => {
                    return {
                        id: item.id,
                        type: item.sort,
                        name: item.drugsname,
                        img: item.img,
                        spec: item.type,
                        price: res.data.data[0].price,
                        num: item.count,
                        time: item.endtime,
                        remark: item.other,
                    }
                })
            })

        })
    }

    const detailOk = () => {  // 详情弹框确认按钮
        setEditModalOpen(false)
    }

    const detailCancel = () => {  // 详情弹框取消按钮
        setEditModalOpen(false)
    }

    const del = (id) => {  // 删除按钮
        setCurrentId(id)
        setTipModalOpen(true);
    }

    const handleOk = () => {  // 确认删除按钮
        axios.get('http://8.148.7.123:8000/recipel/del', {
            params: {
                id: currentId
            }
        }).then(res => {
            console.log(res.data)
            if (res.data.code === 1) {
                message.success('删除成功')
            } else {
                message.error('删除失败')
            }
        })
        setTipModalOpen(false)
    }

    const handleCancel = () => {  // 取消删除按钮
        setTipModalOpen(false)
    }
    const onSelectChange = (newSelectedRowKeys) => {  // 选中项变化时触发
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {  // 行选择器配置
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;  // 是否有选中项
    // 表格列配置
    const columns = [
        {
            title: '医生头像',
            dataIndex: 'head',
            render: (text, record) => (
                <div>
                    <img src={text} alt="医生头像" style={{ width: '50px', height: '50px' }} />
                </div>
            )
        },
        {
            title: '医生姓名',
            dataIndex: 'name',
        },
        {
            title: '科室',
            dataIndex: 'department',
        },
        {
            title: '处方金额',
            dataIndex: 'price',

        },
        {
            title: '操作',
            dataIndex: 'operate',
            render: (text, record) => (
                <div>
                    <FileTextOutlined className='detail_icon' onClick={() => detail(record.id)} />
                    <DeleteOutlined className='delete_icon' onClick={() => del(record.id)} />
                </div>
            )
        },

    ];
    // 处方详情列配置
    const detailColumns = [
        {
            title: '药品类型',
            dataIndex: 'type',
        },
        {
            title: '药品名称',
            dataIndex: 'name',
        },
        {
            title: '药品图片',
            dataIndex: 'img',
            render: (text, record) => (
                <div>
                    <img src={text} alt="药品图片" style={{ width: '50px', height: '50px' }} />
                </div>
            )
        },
        {
            title: '药品规格',
            dataIndex: 'spec',
        },
        {
            title: '药品单价',
            dataIndex: 'price',
        },
        {
            title: '药品数量',
            dataIndex: 'num',
        },
        {
            title: '有效期',
            dataIndex: 'time',
        },
        {
            title: '用量备注',
            dataIndex: 'remark',
        },
    ]
    const [tableData, setTableData] = useState([])  // 表格数据
    const [detailTableData, setDetailTableData] = useState([

    ]);

    // 获取表格数据
    const getTableData = () => {
        axios.get('http://8.148.7.123:8000/recipel/list', {
            params: {
                page: 1,
                size: 100,
            }
        }).then(res => {
            // console.log(res.data)
            setTableData(() => {
                return res.data.data.map(item => {
                    return {
                        ...item,
                        price: item.price.toFixed(2),  // 金额保留两位小数
                    }
                })
            })
        }).catch(err => {
            console.error(err)
        })
    }

    useEffect(() => {
        getTableData();
    }, [])  // 页面加载时获取表格数据
    return <div>
        {/* 删除弹框 */}
        <Modal title="系统提示" open={TipModalOpen} onOk={handleOk} onCancel={handleCancel} cancelText='取消' okText='确认删除'>
            <p>您正在处方信息，此操作不可逆，确定删除吗?</p>
        </Modal>
        {/* 处方详情弹框 */}
        <Modal title="处方详情" width={800} maskClosable={false} open={detailModalOpen} onOk={detailOk} onCancel={detailCancel} cancelText='取消' okText='确定'
            footer={
                <div>
                    总价：{detailTableData[0]?.price * detailTableData[0]?.num}元
                </div>
            }
        >
            <Table
                bordered
                columns={detailColumns}
                dataSource={detailTableData}
                rowKey={'id'}
                size='small'
                pagination={false}
            />
        </Modal>
        <div className="inp_box">
            <div style={{ whiteSpace: 'nowrap' }}>
                <label htmlFor="" style={{ fontWeight: 'bold' }}>医生名称</label>
                <Input className="search_inp" value={doctor} onChange={doctorChange} style={{ width: '240px' }} placeholder="请输入医生名称" />
                <label htmlFor="" style={{ fontWeight: 'bold' }}>处方开具科室</label>
                <Input className="search_inp" value={department} onChange={departmentChange} style={{ width: '240px' }} placeholder="请输入处方科室" />
                <Button type="primary" size="small" icon={<SearchOutlined />} style={{ marginRight: '10px' }} onClick={queryBtn}>查询</Button>
            </div>
            <div>
                <Button type="" size="small" onClick={delChecked} disabled={!hasSelected} loading={loading}>删除选中</Button>
            </div>
        </div>
        <Table
            rowSelection={rowSelection}
            bordered
            columns={columns}
            dataSource={tableData}
            rowKey={'id'}
            size='small'
        />
    </div >
}